<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Repos\ProductRepo;
use DB;



class ProductController extends Controller
{
    public function index(Request $request)
    {
    	$where = [];
    	$data = $request->except(['token','_method','page']);
        $where = array_where($data, function ($value, $key) {
            return $where[$key] = $value;
        });
        $page = $request->page?$request->page:1;
        
        $types = DB::table('product_types')->get();
    	$list = ProductRepo::getListPages($where);    	
    	return view('admin.product.index',compact('list','where','types','page'));
    }


    public function create(Request $request)
    {      
        $types = DB::table('product_types')->get();
        return view('admin.product.add',compact('types'));
    }

    public function store(Request $request)
    {
        $rs['status'] = 'danger';
        $rs['msg']    = '操作失败';
        $data = $request->except(['_token']);
        //dd($data);
        $file = $request->file('pic');

        // 文件是否上传成功
        if ($file->isValid()) {
            $folder = 'pic/';
            $savepath = '/public/'.$folder;
            $filename = uploadFile($file,$savepath);
            $data['pic'] = '/storage/'.$folder.$filename;      
        }
        $flag = ProductRepo::create($data);
        if($flag) {
            $rs['status'] = 'success';
            $rs['msg'] = '操作成功';
            return redirect('zadmin/arts')->with('rs',$rs);
        }
        return back()->with('rs',$rs);
    }

    public function edit($id,Request $request)
    {
        $data = ProductRepo::find(['id'=>$id]);
        $types = DB::table('product_types')->get();
        $page = $request->page?$request->page:1;
        
        return view('admin.product.edit',compact('data','types','page'));
    }

    public function update(Request $request, $id)
    {
        $rs['status'] = 'success';
        
        $data = $request->except(['_token','_method','page']);
        $page = $request->page;
        $file = $request->file('pic');
        // 文件是否上传成功
        if ($file) {
            $folder = 'pic/';
            $savepath = '/public/'.$folder;
            $filename = uploadFile($file,$savepath);
            $data['pic'] = '/storage/'.$folder.$filename;      
        }
       // dd($where,$data);
        $flag = ProductRepo::update($id,$data);
        return redirect('zadmin/arts?page='.$page)->with('rs',$rs);
    }

    public function destroy($id)
    {
        $rs['status'] = 'success';
        ProductRepo::destroy($id);
        return redirect('zadmin/arts')->with('rs',$rs);
    }

   

   
}
